package com.example.biji;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NotificationCompat;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class EditActivity extends BaseActivity {

    private Context context = this;

    EditText et;


    PendingIntent pendingIntent;
    AlarmManager alarmManager;


    private Toolbar myToolbar;
    private String old_content = "";
    private String old_time = "";
    private int old_Tag = 1;
    private long id = 0;
    private int openMode = 0;
    private int tag = 1;
    public Intent intent = new Intent(); // message to be sent
    private boolean tagChange = false;


//    private String channelId = "Notes";
//    private String name = "ChannelName";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_layout);

        //没有用的闹钟
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent1 = new Intent(EditActivity.this,ClockActivity.class);
        pendingIntent = PendingIntent.getActivity(getApplication(), 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);



        //绑定工具栏
        myToolbar = findViewById(R.id.my_Toolbar);


        setSupportActionBar(myToolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); //设置toolbar取代actionbar


        //绑定并设置下拉框
        Spinner mySpinner = (Spinner) findViewById(R.id.spinner);
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        List<String> tagList = Arrays.asList(sharedPreferences.getString("tagListString", null).split("_")); //获取tags
        ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, tagList);
        myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mySpinner.setAdapter(myAdapter);


        //下拉框选项被点击后进行参数修改
        mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                tag = (int) id + 1;
                tagChange = true;

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

//        intent1 = new Intent(EditActivity.this, ClockActivity.class);
//
//        pendingIntent = PendingIntent.getActivity(EditActivity.this, 2, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
//        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

//        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            NotificationChannel channel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_DEFAULT);
//            // Register the channel with the system; you can't change the importance
//            // or other notification behaviors after this
//            channel.enableVibration(true);
//            manager.createNotificationChannel(channel);
//        }


        //返回键被点击后，进行数据设置并保存
        myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                autoSetMessage();
                setResult(RESULT_OK, intent);
                finish();
            }
        });


        //绑定编辑框
        et = findViewById(R.id.et);


        Intent getIntent = getIntent();
        openMode = getIntent.getIntExtra("mode", 0);

        //设置一些固定变量
        if (openMode == 3) {//打开已存在的note
            id = getIntent.getLongExtra("id", 0);
            old_content = getIntent.getStringExtra("content");
            old_time = getIntent.getStringExtra("time");
            old_Tag = getIntent.getIntExtra("tag", 1);
            et.setText(old_content);
            et.setSelection(old_content.length());
        }
    }



    @Override
    protected void needRefresh() {
        Log.d(TAG, "needRefresh: Edit");
        setNightMode();
        Intent intent = new Intent(this, EditActivity.class);
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.edit_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.delete:
                new AlertDialog.Builder(EditActivity.this)
                        .setMessage("删除吗？")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (openMode == 4) { // new note
                                    intent.putExtra("mode", -1);
                                } else { // existing note
                                    intent.putExtra("mode", 2);
                                    intent.putExtra("id", id);
                                }
                                setResult(RESULT_OK, intent);
                                finish();
                            }
                        }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();
                break;
            case R.id.clock:
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(System.currentTimeMillis());
                calendar.add(Calendar.SECOND,3);
                alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
                Toast.makeText(EditActivity.this, "闹钟设置完成", Toast.LENGTH_SHORT).show();
                break;

//                NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"channel");
//                builder.setSmallIcon(R.drawable.abc_vector_test);
//                builder.setContentTitle("通知");
//                builder.setContentText("好不了了");
//                builder.setDefaults(Notification.DEFAULT_ALL);
//                Notification notification = builder.build();
//                manager.notify(0x1,notification);




//                new TimePickerDialog(EditActivity.this, 0, (timePicker, i, i1) -> {
//                    Calendar calendar1 = Calendar.getInstance();
//                    calendar1.setTimeInMillis(System.currentTimeMillis());
//                    calendar1.set(Calendar.HOUR, i);
//                    calendar1.set(Calendar.MINUTE, i1);
//                    alarmManager.set(AlarmManager.RTC_WAKEUP,calendar1.getTimeInMillis(),pendingIntent);
//                    Toast.makeText(EditActivity.this, "闹钟设置完毕~", Toast.LENGTH_SHORT).show();
//                },calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),false).show();


        }
        return super.onOptionsItemSelected(item);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            autoSetMessage();
            setResult(RESULT_OK, intent);

            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    public void autoSetMessage() {
        if (openMode == 4) {
            if (et.getText().toString().length() == 0) {
                intent.putExtra("mode", -1); //nothing new happens.
            } else {
                intent.putExtra("mode", 0); // new one note;
                intent.putExtra("content", et.getText().toString());
                intent.putExtra("time", dateToStr());
                intent.putExtra("tag", tag);
            }
        } else {
            if (et.getText().toString().equals(old_content) && !tagChange)
                intent.putExtra("mode", -1); // edit nothing
            else {
                intent.putExtra("mode", 1); //edit the content
                intent.putExtra("content", et.getText().toString());
                intent.putExtra("time", dateToStr());
                intent.putExtra("id", id);
                intent.putExtra("tag", tag);

            }
        }
    }

    public String dateToStr() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(date);
    }
}